package jmine.tec.rpc.common.serialization.json;

import jmine.tec.json.JSON;
import jmine.tec.json.JSONObject;
import jmine.tec.json.JSONString;
import jmine.tec.rpc.RPCMessages;
import jmine.tec.rpc.common.RPCException;

/**
 * Conversor de JSON para Java e vice-versa
 * 
 * @author lundberg
 */
public class JSONEnumConverter extends AbstractJSONObjectConverter implements JSONConverterStrategy {

    /**
     * {@inheritDoc}
     */
    public boolean matchesJava(Object object) {
        return object instanceof Enum;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected JSON objectType() {
        return new JSONString("enum");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    protected Object instantiate(JSONConversionContext context, JSON json) {
        Class<? extends Enum> enumClass = (Class<? extends Enum>) context.toJava(json.getProperty("&class"));
        try {
            return Enum.valueOf(enumClass, (String) context.toJava(json.getProperty("value")));
        } catch (IllegalArgumentException e) {
            throw new RPCException(RPCMessages.INVALID_DATE_VALUE.create(json.getProperty("value")), e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillObject(JSONConversionContext context, JSON json, Object object) {
        // OK
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillJSON(JSONConversionContext context, Object object, JSONObject json) {
        json.setProperty("&class", context.toJSON(object.getClass()));
        json.setProperty("value", context.toJSON(((Enum) object).name()));
    }
}
